package com.gamecauca.android;




import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import com.gamecauca.screen.MainMenuScreen;
import com.scoreloop.client.android.core.controller.RequestCancelledException;
import com.scoreloop.client.android.core.controller.RequestController;
import com.scoreloop.client.android.core.controller.RequestControllerObserver;
import com.scoreloop.client.android.core.controller.ScoresController;

import com.scoreloop.client.android.core.model.Score;
import com.scoreloop.client.android.core.model.ScoreFormatter;
import com.scoreloop.client.android.core.model.Session;
import com.scoreloop.client.android.core.model.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class LeaderboardActivity extends Activity{

	// we'll reuse the ScoresController, so let's store it here
	private ScoresController			scoresController;
	// together with the observer
	private RequestControllerObserver	observer;
	
	// constants for the dialogs we need
	private final static int			DIALOG_ERROR				= 0;
	private final static int			DIALOG_PROGRESS				= 1;
	private final static int			DIALOG_SYNC_SUCCESS			= 2;
	private final static int			DIALOG_SYNC_ERROR			= 3;
	
	// hold references to some UI elements
	private Spinner						spinnerModes;
	private Button						buttonPrev;
	private Button						buttonNext;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.leaderboard);
		
		// find our buttons
		buttonPrev = (Button) findViewById(R.id.button_page_prev);
		buttonNext = (Button) findViewById(R.id.button_page_next);

		// find the spinner that selects the mode
		spinnerModes = (Spinner) findViewById(R.id.spinnerModes);
		
		// fill an adapter with the mode names
		ArrayAdapter<CharSequence> adapterModes = ArrayAdapter.createFromResource(this, R.array.mode_names,
				android.R.layout.simple_spinner_item);
		adapterModes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		// put the adapter into the spinner
		spinnerModes.setAdapter(adapterModes);
		
		// set up the request observer for all leaderboard requests
		observer = new RequestControllerObserver() {

			@Override
			public void requestControllerDidFail(final RequestController aRequestController, final Exception anException) {
				// TODO Auto-generated method stub
				// if it's a RequestCancelledException we just started a new request.
				// so that's fine, just keep going...
				if (!(anException instanceof RequestCancelledException)) {
					dismissDialog(DIALOG_PROGRESS);
					showDialog(DIALOG_ERROR);
				}

				buttonNext.setVisibility(View.GONE);
				buttonPrev.setVisibility(View.GONE);
			}

			@Override
			public void requestControllerDidReceiveResponse(
					final RequestController requestController) {
				// TODO Auto-generated method stub
				
				// we received a leaderboard, display it in the ListView

				// get the scores from our controller
				final ScoresController scoresController = (ScoresController) requestController;
				final List<Score> scores = scoresController.getScores();

				// find the list
				final ListView leaderboardList = (ListView) findViewById(R.id.leaderboard_list);
				
				// set up an adapter for our list view
				final ListAdapter adapter = new ArrayAdapter<Score>(LeaderboardActivity.this, android.R.layout.simple_list_item_1, scores) {
					
					@Override
					public View getView(int position, View view, ViewGroup parent) {
						
						if (view == null) {
							view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
									R.layout.leaderboard_listitem, null);
						}

						Score score = getItem(position);
						User user = score.getUser();

						// set username
						((TextView) view.findViewById(R.id.leaderboard_listitem_username)).setText(user.getDisplayName());

						// set rank
						((TextView) view.findViewById(R.id.leaderboard_listitem_rank)).setText(score.getRank().toString());

						// set score result
						((TextView) view.findViewById(R.id.leaderboard_listitem_score)).setText(ScoreFormatter.format(score));
						
						// set avatar
						final ImageView profilePic = (ImageView) view.findViewById(R.id.leaderboard_listitem_icon);
						// we'll use an AsyncTask to download the picture in background
						(new AsyncTask<String, Void, Bitmap>() {

							@Override
							protected Bitmap doInBackground(String... params) {
								Bitmap result = null;
								try {
									URLConnection urlConnection = new URL(params[0]).openConnection();
									// use caching
									urlConnection.setUseCaches(true);
									result = BitmapFactory.decodeStream(urlConnection.getInputStream());
								} catch (Exception e) {
									// do nothing
								}
								return result;
							}

							protected void onPreExecute() {
								profilePic.setImageResource(R.drawable.sl_icon_loading);
							}

							protected void onPostExecute(Bitmap result) {
								if (result != null) {
									profilePic.setImageBitmap(result);
								} else {
									profilePic.setImageResource(R.drawable.sl_icon_user);
								}
							}
						}).execute(user.getImageUrl());
						
						// if the user is the current user, we change the background color
						if (user.equals(Session.getCurrentSession().getUser())) {
							view.setBackgroundColor(Color.LTGRAY);
						} else {
							view.setBackgroundColor(Color.WHITE);
						}

						return view;
					}
				};
				
				// put the adapter into the list
				leaderboardList.setAdapter(adapter);

				// show or hide the prev/next buttons
				buttonNext.setVisibility(scoresController.hasNextRange() ? View.VISIBLE : View.GONE);
				buttonPrev.setVisibility(scoresController.hasPreviousRange() ? View.VISIBLE : View.GONE);

				// we're done!
				dismissDialog(DIALOG_PROGRESS);
			}
			
		};
		
		// set up a ScoresController with our observer
		scoresController = new ScoresController(observer);

		// we want to get 20 entries per request
		scoresController.setRangeLength(20);
		
		// set up a click listener for the mode select spinner
		spinnerModes.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// set the mode
				scoresController.setMode(position);

				// show a progress dialog while we're waiting
				showDialog(DIALOG_PROGRESS);

				// load scores starting from the first place
				scoresController.loadRangeAtRank(1);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		buttonNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// show a progress dialog while we're waiting
				showDialog(DIALOG_PROGRESS);

				// tell the controller to load the next range
				scoresController.loadNextRange();
			}
		});
		
		buttonPrev.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// show a progress dialog while we're waiting
				showDialog(DIALOG_PROGRESS);

				// tell the controller to load the previous range
				scoresController.loadPreviousRange();
			}
		});
		
	}
	
	// handler to create our dialogs
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_PROGRESS:
			return ProgressDialog.show(LeaderboardActivity.this, "", getString(R.string.loading));
		case DIALOG_ERROR:
			return (new AlertDialog.Builder(this)).setMessage(R.string.leaderboard_error).setPositiveButton(R.string.too_bad, null)
					.create();
		case DIALOG_SYNC_SUCCESS:
			return (new AlertDialog.Builder(this)).setMessage(R.string.score_submitted).setTitle(R.string.scoreloop)
					.setIcon(getResources().getDrawable(R.drawable.sl_icon_user)).setPositiveButton(R.string.awesome, null).create();
		case DIALOG_SYNC_ERROR:
			return (new AlertDialog.Builder(this)).setMessage(R.string.score_submit_error).setPositiveButton(R.string.too_bad, null)
					.create();
		}
		return null;
	}
	
	
}
